package com.zjj.concurrent.thread;

/**
 * @author zhanglei.zjj
 * @description 并发编程，线程优先级测试
 * @date 2023/5/15 22:27
 */
public class TestSellTicket implements Runnable {
    /**
     * 车票
     */
    private int ticket;

    /**
     * 1线程卖出的车票
     */
    private int aNum = 0;

    /**
     * 2线程卖出的车票
     */
    private int bNum = 0;

    /**
     * 3线程卖出的车票
     */
    private int cNum = 0;

    /**
     * 4线程卖出的车票
     */
    private int dNum = 0;

    private boolean canPrint = true;

    public TestSellTicket() {
        this.ticket = 1000;
    }

    @Override
    public void run() {
        while (ticket > 0) {
            synchronized (this) {
                if (ticket > 0) {
                    try {
                        // 线程进入暂时的休眠
                        Thread.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // 记录每个线程卖出的车票
                    String threadName = Thread.currentThread().getName();
                    ticket --;
                    switch (threadName) {
                        case "thread1" :
                            aNum ++;
                            break;
                        case "thread2" :
                            bNum ++;
                            break;
                        case "thread3" :
                            cNum ++;
                            break;
                        case "thread4" :
                            dNum ++;
                            break;
                    }
                }
                if (ticket <=0 && canPrint) {
                    System.out.println("1线程卖出车票：" + aNum);
                    System.out.println("2线程卖出车票：" + bNum);
                    System.out.println("3线程卖出车票：" + cNum);
                    System.out.println("4线程卖出车票：" + dNum);

                    canPrint = false;
                }
            }
            // Thread.yield();
        }
    }

    public static void main(String[] args) {
        TestSellTicket demo = new TestSellTicket();

        Thread thread1 = new Thread(demo, "thread1");
        Thread thread2 = new Thread(demo, "thread2");
        Thread thread3 = new Thread(demo, "thread3");
        Thread thread4 = new Thread(demo, "thread4");
        //priority优先级默认是5，最低1，最高10
        thread1.setPriority(Thread.MAX_PRIORITY);
        thread2.setPriority(Thread.MAX_PRIORITY);
        thread3.setPriority(Thread.MIN_PRIORITY);
        thread4.setPriority(Thread.MIN_PRIORITY);
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

    }
}
